import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { RouteRecordRaw ,RouteMeta} from "vue-router"
import { constantRoutes, asyncRoutes } from "@/router"
import { flatMultiLevelRoutes } from "@/router/helper"
import routeSettings from "@/config/route"
const Layouts = () => import("@/layouts/index.vue")

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true
}

const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tempRoute = { ...route }
    if (hasPermission(roles, tempRoute)) {
      if (tempRoute.children) {
        tempRoute.children = filterAsyncRoutes(tempRoute.children, roles)
      }
      res.push(tempRoute)
    }
  })
  return res
}

type Permission = {
  id: number;
  name: string;
  description: string;
  path:string;
  url: string;
  order: number;
  icon: string | null;
  type: number;
  children: Permission[];
};

const viewsComponent: Record<string, RouteMeta> = import.meta.glob("/src/views/**/*.vue", { eager: true })

const generateRoutes = (permissions: Permission[]): RouteRecordRaw[] => {
  const routes: RouteRecordRaw[] = [];
  permissions.forEach(permission => {
    if (permission.type === 1) {
      const route: RouteRecordRaw = {
        path: permission.path,
        name: permission.name,
        component: permission.children && permission.children.length > 0
          ? Layouts // 假设Layout是布局组件
          : () => {
            const filepath = `/src/views${permission.url}.vue`
            return viewsComponent[filepath]
          },
        meta: {
          title: permission.name,
          svgIcon: permission.icon ? permission.icon : "menu",
        },
        children: permission.children && permission.children.length > 0 ? generateRoutes(permission.children) : undefined
      };
      routes.push(route);
    }
  });
  return routes;
};


export const usePermissionStore = defineStore("permission", () => {
  const routes = ref<RouteRecordRaw[]>([])
  const dynamicRoutes = ref<RouteRecordRaw[]>([])
  const permissions = ref<Permission[]>([])
  const setRoutes = (roles: string[]) => {
    //静态路由
    const accessedRoutes = routeSettings.async ? filterAsyncRoutes(asyncRoutes, roles) : asyncRoutes
    //动态路由.
    const dynamicRoutesFromPermissions = generateRoutes(permissions.value)
    routes.value = constantRoutes.concat(accessedRoutes, dynamicRoutesFromPermissions)
    dynamicRoutes.value = routeSettings.thirdLevelRouteCache
      ? flatMultiLevelRoutes([...accessedRoutes, ...dynamicRoutesFromPermissions])
      : accessedRoutes.concat(dynamicRoutesFromPermissions)
  }

  const setPermissions = (perms: Permission[]) => {
    permissions.value = perms
  }

  return { routes, dynamicRoutes, setRoutes, permissions, setPermissions }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
